package com.thebeastshop.hotlink.springboot;

import cn.hutool.core.util.StrUtil;
import com.thebeastshop.hotlink.spring.HotkeyInit;
import com.thebeastshop.hotlink.spring.HotlinkConfig;
import com.thebeastshop.hotlink.spring.HotlinkScanner;
import com.thebeastshop.hotlink.springboot.property.HotlinkProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Random;

@Configuration
@EnableConfigurationProperties(HotlinkProperty.class)
@ConditionalOnProperty(prefix = "hotlink", name = "etcd-url")
public class HotlinkAutoConfiguration {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Bean
    public HotlinkConfig hotlinkConfig(HotlinkProperty hotlinkProperty, Environment environment){
        HotlinkConfig hotlinkConfig = new HotlinkConfig();
        hotlinkConfig.setEtcdUrl(hotlinkProperty.getEtcdUrl());
        if (StrUtil.isBlank(hotlinkProperty.getAppName())){
            hotlinkConfig.setAppName(environment.getProperty("app.name"));
            if (StrUtil.isBlank(hotlinkConfig.getAppName())){
                hotlinkConfig.setAppName(environment.getProperty("spring.application.name"));
                if (StrUtil.isBlank(hotlinkConfig.getAppName())){
                    hotlinkConfig.setAppName(StrUtil.format("unknown{}", new Random().nextInt(1000)));
                }
            }
        }else{
            hotlinkConfig.setAppName(hotlinkProperty.getAppName());
        }
        log.info("[Hotlink] appName:{} etcdUrl:{}", hotlinkConfig.getAppName(), hotlinkConfig.getEtcdUrl());
        return hotlinkConfig;
    }

    @Bean
    public HotkeyInit hotkeyInit(HotlinkConfig hotlinkConfig){
        return new HotkeyInit(hotlinkConfig);
    }

    @Bean
    public HotlinkScanner hotlinkScanner(){
        return new HotlinkScanner();
    }
}
